package com.study.spmongodb.wwj.thread.char09;

import java.util.stream.Stream;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/6 15:01
 */
public class ProduceConsumerVersion3 {

    private int i = 0;

    private final Object LOCK = new Object();

    private volatile boolean isProduced = false;

    public void produce() {
        synchronized (LOCK) {
            while (isProduced) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("p>------" + i++);
            LOCK.notify();
            isProduced = true;
        }
    }

    public void consume() {
        synchronized (LOCK) {
            while (!isProduced) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("c>--" + i);
            LOCK.notify();
            isProduced = false;
        }
    }

    /**
     * 单个 消费者，单个生产者没问题。
     *
     * @param args
     */
    public static void main(String[] args) {
        final ProduceConsumerVersion3 pc = new ProduceConsumerVersion3();

        Stream.of("p1", "p2").forEach(h -> {
            new Thread(() -> {
                while (true) {
                    pc.produce();
                }
            }, h).start();
        });
        Stream.of("c1", "c2").forEach(h -> {
            new Thread(() -> {
                while (true) {
                    pc.consume();
                }
            }, h).start();
        });
    }
}
